<template>
    <div class="mapContainer">
        <div class="left_search">
            <el-input v-model="input" placeholder="请输入会议活动地址" @input="addressInput"></el-input>
            <el-button type="primary" @click>查询</el-button>
            <div id="panel" v-show="showPanel" class="panel"></div>
            <div id="addressLoading" class="addressLoading">正在加载...</div>
        </div>
        <div class="topTip" v-if="curentAddress">
            当前选中的地址为：
            <span
                v-if="curentAddress.formattedAddress"
            >{{ curentAddress.formattedAddress }}</span>
            <span
                v-else-if="curentAddress.pname"
            >{{ curentAddress.pname + curentAddress.cityname + curentAddress.adname + curentAddress.address + curentAddress.name }}</span>
            <span v-else>{{ curentAddress.address }}</span>
        </div>
        <div id="container"></div>
    </div>
</template>

<script>
import { clearTimeout, setTimeout } from 'timers';
export default {
    props: {
        location: {
            type: Object,
            default: () => {},
        },
    },
    data() {
        return {
            input: '',
            placeSearch: {},
            curentAddress: '',
            geocoder: new AMap.Geocoder({
                city: '010', //城市设为北京，默认：“全国”
                radius: 1000, //范围，默认：500
            }),
            timer: null,
            showPanel: false,
            map: {},
        };
    },
    mounted() {
        this.initMap(this.location);

    },
    methods: {
        initMap(location) {
            this.showPanel = false; 
            var center = null;
            var zoom = 12;
            if (
                JSON.stringify(location) !== '{}' &&
                JSON.stringify(location.location) !== '{}'
            ) {
                this.curentAddress = location;
                center = [location.location.lng, location.location.lat];
                zoom = 16;
            }
            var me = this;
            // 初始化地图
            me.map = new AMap.Map('container', {
                resizeEnable: true,
                zoom: zoom,
                center: center,
            });
            // 同时引入工具条插件，比例尺插件和鹰眼插件
            AMap.plugin(
                [
                    'AMap.ToolBar',
                    'AMap.Scale',
                    'AMap.OverView',
                    'AMap.MapType',
                    'AMap.Geolocation',
                ],
                function() {
                    // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
                    me.map.addControl(new AMap.ToolBar());

                    // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
                    me.map.addControl(new AMap.Scale());

                    // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
                    me.map.addControl(new AMap.OverView({ isOpen: true }));

                    // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
                    me.map.addControl(new AMap.MapType());

                    // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
                    me.map.addControl(new AMap.Geolocation());
                }
            );

            // 配置搜索框
            AMap.service(['AMap.PlaceSearch'], function() {
                //构造地点查询类
                var placeSearch;
                me.placeSearch = new AMap.PlaceSearch({
                    pageSize: 4, // 单页显示结果条数
                    pageIndex: 1, // 页码
                    type:
                        '汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施',
                    citylimit: true,
                    // citylimit: true,  //是否强制限制在设置的城市内搜索
                    map: me.map, // 展现结果的地图实例
                    panel: 'panel', // 结果列表将在此容器中进行展示。
                    autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
                });
                // 添加全局的方法，在dom操作的时候调用
                window.aMapSelfEvent = {};
                window.aMapSelfEvent.confirmSearch = function() {
                    me.confirmSearch();
                };
                var initlalAmap = true;
                function addButton() {
                    let div = document.createElement('div');
                    div.innerHTML =
                        "<button class='mapBtn' onclick='aMapSelfEvent.confirmSearch()'>这里是活动地址</button>";
                    document
                        .querySelector(
                            '#container .amap-lib-infowindow-content-wrap'
                        )
                        .appendChild(div);
                }

                me.placeSearch.on('selectChanged', function(result) {
                    if (initlalAmap) {
                        initlalAmap = false;
                        setTimeout(function() {
                            addButton();
                        }, 100);
                    } else {
                        addButton();
                    }

                    me.curentAddress = result.selected.data;
                });
            });

            // 配置手动标点
            var marker = new AMap.Marker();
            me.map.add(marker);

            marker.on('click', function() {
                infoWindow.open(me.map, marker.getPosition());
            });

            var infoWindow = new AMap.InfoWindow({
                offset: new AMap.Pixel(0, -20),
                closeWhenClickMap: true,
                autoMove: false,
            });

            var closeInfoWindow = function() {
                infoWindow.close();
            };

            me.map.on('zoomstart', closeInfoWindow);

            me.map.on('movestart', closeInfoWindow);
            // var geocoder;
            function regeoCode(lnglat) {
                if (!me.geocoder) {
                    me.geocoder = new AMap.Geocoder({
                        city: '010', //城市设为北京，默认：“全国”
                        radius: 1000, //范围，默认：500
                    });
                }

                var lnglatArray = [lnglat.lng, lnglat.lat];
                me.geocoder.getAddress(lnglatArray, function(status, result) {
                    if (status === 'complete' && result.regeocode) {
                        var address = result.regeocode.formattedAddress;
                        var ac = result.regeocode.addressComponent;

                        var info = [];

                        window.aMapSelfEvent.directionThis = function() {
                            ac.location = lnglat;
                            ac.formattedAddress = address;
                            me.confirmSearch(ac);
                        };
                        // info.push(
                        //   "<div class='input-card content-window-card'><div><img style='float:left;' src=' https://webapi.amap.com/images/autonavi.png '/></div> "
                        // );
                        info.push(
                            "<div style='padding:7px 0px 0px 0px;'><p>城市:" +
                                ac.province +
                                ' ' +
                                ac.city +
                                ' ' +
                                ac.district +
                                '</p>'
                        );
                        info.push(
                            '<p>地址 :' +
                                ac.street +
                                '' +
                                ac.streetNumber +
                                ' </p>'
                        );
                        info.push('<p>建筑 :' + address + '</p>');
                        info.push(
                            "<p style='margin-top:12px'><button class='mapBtn' onclick='aMapSelfEvent.directionThis()'>这里是活动地址</button></p></div></div>"
                        );
                        infoWindow.setContent(info.join(''));
                        infoWindow.open(me.map, lnglatArray);
                        marker.setPosition(lnglatArray);
                    } else {
                        log.error('根据经纬度查询地址失败');
                    }
                });
            }

            me.map.on('click', function(e) {
                regeoCode(e.lnglat);
            });
        },
        clearSearchList(){
          var a = document.getElementsByClassName("amap_lib_placeSearch")[0];
          if(a){
            a = null
          }
        },
        ok() {
          console.log('object');
            var res = {};
            var curAddr = this.curentAddress;
            if (curAddr) {
                res.formattedAddress = res.address = 
                   ( curAddr.formattedAddress ||
                    curAddr.pname +  curAddr.cityname + curAddr.adname + curAddr.address+ curAddr.name);
                res.location = curAddr.location;
                return res;
            } else {
                this.$message.error('还没有选择地址哦！');
            }
        },
        confirmSearch(result) {
            var me = this;
            if (result == null) {
                result = this.curentAddress;

                var lnglatArray = [result.location.lng, result.location.lat];
                this.geocoder.getAddress(lnglatArray, function(
                    status,
                    result1
                ) {
                    if (status === 'complete' && result1.regeocode) {
                        var address = result1.regeocode.formattedAddress;
                    } else {
                        log.error('根据经纬度查询地址失败');
                    }
                });
            } else {
                this.curentAddress = result;
            }
        },
        addressInput() {
            clearTimeout(this.timer);
            this.timer = setTimeout(() => {
                console.log('object');
                var content = this.input;
                document.getElementById('addressLoading').style.display =
                    'block';
                this.showPanel = false;
                var me = this;
                this.placeSearch.search(content, function(status, result) {
                    me.showPanel = true;
                    document.getElementById('addressLoading').style.display =
                        'none';
                });
            }, 600);
        },
    },
};
</script>

<style lang="scss">
.mapContainer {
    position: relative;
    width: 100%;
    height: 100%;
    .left_search {
        position: absolute;
        top: 0;
        left: 0;
        width: 300px;
        bottom: 60px;
        .el-input {
            width: 220px;
        }
        .addressLoading {
            display: none;
            position: absolute;
            width: 100%;
            text-align: center;
            top: 120px;
        }
        .panel {
            margin-top: 10px;
        }
    }
}
#container {
    position: absolute;
    top: 40px;
    bottom: 0;
    left: 300px;
    right: 0;
}
.topTip {
    position: absolute;
    left: 320px;
    top: 0;
    height: 40px;
    span {
        // @extend color-blue;
        @include color-blue;
    }
}

.mapBtn {
    outline: 0;
    display: inline-block;
    font-weight: 400;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    border: 1px solid transparent;
    transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
        border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
    background-color: transparent;
    background-image: none;
    color: #25a5f7;
    border-color: #25a5f7;
    margin: 0.5rem 0 0 3rem;
    padding: 0.25rem 1rem;
    line-height: 1.5;
    border-radius: 1rem;
    -webkit-appearance: button;
    cursor: pointer;
}
.mapBtn:hover {
    background-color: #25a5f7;
    color: #fff;
}
</style>